<template>
  <div class="box">
    <a-tabs
      style="background: #ffff; height: 100%"
      v-model:activeKey="activeKey"
      @change="handleTabChange"
    >
      <template #rightExtra>
        <a-button
          type="primary"
          v-if="activeKey == 'list'"
          ghost
          @click="settlementCycle"
          >设置结算周期</a-button
        >
      </template>

      <a-tab-pane key="rule" tab="佣金规则">
        <div class="rule-box">
          <a-row :gutter="[8, 12]" class="content">
            <a-col :span="8" @click="addRule">
              <a-card class="add-template"> <PlusOutlined /> 新增模板 </a-card>
            </a-col>

            <a-col :span="8" v-for="item in ruleList">
              <a-card class="templat-list">
                <a-card-meta class="card-list">
                  <template #title>
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                      "
                    >
                      <span>{{ item.name }}</span>
                      <span
                        v-if="item.status == 1"
                        style="color: #2681f3; font-size: 13px"
                        >生效中
                      </span>
                      <span v-else style="color: red; font-size: 13px"
                        >禁用中</span
                      >
                    </div>
                  </template>
                  <template #description>
                    <div class="rule-text">
                      <span
                        >升档方式：{{
                          item.compute_type == 1
                            ? "无升档"
                            : item.compute_type == 2
                            ? "合同数量"
                            : "合同金额"
                        }}</span
                      >
                    </div>
                    <div class="rule-text">
                      <span
                        >提成比例：

                        <span>{{ item?.divide_config[0].title }}&nbsp; </span>
                        <span
                          >下限：{{ item?.divide_config[0].threshold }}&nbsp;
                        </span>
                        <span
                          >比例：{{ item?.divide_config[0].divide_num }}</span
                        >
                        <!-- <span
                          >{{ item?.divide_config[0].divide_unit }}&nbsp;</span
                        > -->
                        <span
                          >{{ item.divide_type == 3 ? "元" : "%" }}&nbsp;</span
                        >
                      </span>
                      <a-tooltip>
                        <template #title>
                          <div v-for="config in item.divide_config">
                            <span>档位：{{ config.title }} &nbsp;</span>
                            <span
                              >档位下限：{{
                                config.threshold == "0.00"
                                  ? 0
                                  : config.threshold
                              }}&nbsp;
                            </span>
                            <span>提成比例：{{ config.divide_num }}&nbsp;</span>
                            <!-- <span>{{ config.divide_unit }}&nbsp;</span> -->
                            <span
                              >{{
                                item.divide_type == 3 ? "元" : "%"
                              }}&nbsp;</span
                            >
                          </div>
                        </template>
                        <more-outlined style="color: #2681f3" />
                      </a-tooltip>
                    </div>
                    <div class="rule-text">
                      <span>匹配人员：{{ item.match_numbers }}个</span>
                    </div>
                    <div class="rule-text">
                      <span>更新时间：{{ item.updated_at || "--" }}</span>
                      <div
                        type="link"
                        style="
                          display: inline-block;
                          margin-left: 5px;
                          color: #2681f3;
                          cursor: pointer;
                        "
                        @click="logInfo(item)"
                      >
                        日志
                      </div>
                    </div>
                  </template>

                  <template #avatar>
                    <cu-icon type="org-fapiao" class="icon"></cu-icon>
                  </template>
                </a-card-meta>
                <template class="ant-card-actions" #actions>
                  <span @click="editRule(item.id)"
                    ><EditOutlined />&nbsp;&nbsp;编辑</span
                  >
                  <span @click="changeRule(item)">
                    <UnlockOutlined v-if="item.status == 0" />
                    <LockOutlined v-else />&nbsp;&nbsp;<span>{{
                      item.status == 0 ? "启用" : "禁用"
                    }}</span></span
                  >
                </template>
              </a-card>
            </a-col>
          </a-row>
        </div>
        <div style="text-align: right; height: 50px; padding-right: 15px">
          <a-pagination
            v-model:current="page"
            :total="total"
            showSizeChanger
            @change="handlePageChange"
          />
        </div>
      </a-tab-pane>
      <a-tab-pane key="list" tab="结算列表">
        <SettlementList ref="settlement" :activeKey="activeKey" />
      </a-tab-pane>
    </a-tabs>

    <!-- 新增、编辑佣金规则 -->
    <CommissionRule
      :visible="ruleVisible"
      :editId="editId"
      @close="ruleClose"
      @save="refreshList"
    />

    <!-- 修改日志 -->
    <a-drawer
      v-model:visible="logVisible"
      title="修改日志"
      closable
      @close="onClose"
    >
      <a-list :dataSource="logList">
        <template #renderItem="{ item, index }">
          <a-list-item>
            <div
              @click="showLogDetail(item, index)"
              style="width: 100%; color: #1e90ff"
            >
              <div>
                <span
                  style="
                    display: inline-block;
                    width: 10px;
                    height: 10px;
                    border-radius: 5px;
                    margin-right: 5px;
                    border: 2px solid #1e90ff;
                  "
                ></span>
                <span class="mr-10">{{ item.created_at }}</span>
                <a-tag color="#f00" v-if="index == 0">当前版本</a-tag>
              </div>
              <div style="margin-left: 15px">
                <span>修改人：</span>
                <span>{{ item?.operate_user?.realname }}</span>
                <span>{{ item?.operate_user?.phone }}</span>
                <right-outlined />
              </div>
            </div>
          </a-list-item>
        </template>
      </a-list>
    </a-drawer>

    <!-- 修改日志详情 -->
    <a-drawer
      v-model:visible="logDetailVisible"
      title="修改日志"
      closable
      @close="onCloseDetail"
    >
      <div style="text-align: center; font-size: 14px">
        <span style="display: block; color: #1e90ff">
          <span>{{ logItem.created_at }} 提交成功</span> <span>修改人：</span>
          <span>{{ logItem?.operate_user?.realname }}</span>
          <span>{{ logItem?.operate_user?.phone }}</span>
        </span>
        <span style="display: block">
          升档方式：{{
            logItem.compute_type == 1
              ? "无升档"
              : logItem.compute_type == 2
              ? "合同数量"
              : "合同金额"
          }}
        </span>

        <span style="display: block">
          提成方式：{{
            logItem.content.divide_type == 1
              ? "固定比例"
              : logItem.content.divide_type == 2
              ? "阶梯比例"
              : "阶梯固定金额"
          }}
        </span>
        <span style="display: block">
          状态：{{ logItem.index == 0 && logStatus == 1 ? "正常" : "禁用" }}
        </span>
      </div>

      <div class="log-title">销售提成</div>
      <a-table
        bordered
        :pagination="false"
        :columns="commissionColumns"
        :dataSource="divide_config"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key == 'title'">
            {{ record[column.key] }}</template
          >
          <template v-if="column.key == 'threshold'">
            {{ record["threshold"] == "0.00" ? 0 : record["threshold"] }}
          </template>
          <template v-if="column.key == 'divide_num'">
            {{ record.divide_num
            }}{{ logItem.content.divide_type == 3 ? "元" : "%" }}</template
          >
        </template>
      </a-table>
      <div class="log-title">管理提成</div>
      <a-table
        bordered
        :pagination="false"
        :columns="commissionColumns"
        :dataSource="manage_config"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key == 'title'">
            {{ record[column.key] }}</template
          >
          <template v-if="column.key == 'threshold'">
            {{ record["threshold"] == "0.00" ? 0 : record["threshold"] }}
          </template>
          <template v-if="column.key == 'divide_num'">
            {{ record.divide_num
            }}{{ logItem.content.divide_type == 3 ? "元" : "%" }}</template
          >
        </template>
      </a-table>

      <div class="log-title">渠道提成</div>
      <a-table
        bordered
        :pagination="false"
        :columns="commissionColumns"
        :dataSource="channel_config"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key == 'title'">
            {{ record[column.key] }}</template
          >
          <template v-if="column.key == 'threshold'">
            {{ record["threshold"] == "0.00" ? 0 : record["threshold"] }}
          </template>
          <template v-if="column.key == 'divide_num'">
            {{ record.divide_num
            }}{{ logItem.content.divide_type == 3 ? "元" : "%" }}</template
          >
        </template>
      </a-table>
    </a-drawer>

    <!-- 结算周期 -->
    <a-modal
      v-model:visible="cycleVisible"
      title="结算周期"
      :width="'600px'"
      @ok="handleOk"
      @close="cycleVisible = false"
    >
      <a-alert type="warning">
        <template #description>
          <p>
            1、结算周期一旦设置将按照这个周期计算提成，到结算日期后，系统会自动生成结算明细
          </p>
          <p>2、更改不影响已经结算列表的数据</p>
        </template>
      </a-alert>

      <div class="flex mt-10">
        <div class="mr-10">
          <span>设置结算周期:</span>
        </div>
        <div>
          <div>
            <a-radio
              :checked="settle_param.settle_type == 1"
              @change="changeSettleType"
              >按自然月</a-radio
            >
          </div>
          <div>
            <a-radio
              :checked="settle_param.settle_type == 2"
              @change="changeSettleType"
              >以每个月的
              <a-input-number
                min="1"
                max="31"
                :precision="0"
                v-model:value="settle_param.date"
              ></a-input-number>
              号开始一个月</a-radio
            >
          </div>
        </div>
      </div>

      <div class="flex mt-10">
        <div class="mr-10">
          <span>设置结算方式:</span>
        </div>
        <div style="flex: 1">
          <div class="flex" style="align-items: flex-start">
            <div style="width: 100px">
              <a-radio
                :checked="settle_param.compute_type == 1"
                @change="changeComputeType"
                >手动结算</a-radio
              >
            </div>
            <span style="font-size: 11px; flex: 1; margin-top: 3px">
              到结算日期后需要在结算列表手动生成付款单
            </span>
          </div>
          <div class="flex" style="align-items: flex-start">
            <div style="width: 100px">
              <a-radio
                :checked="settle_param.compute_type == 2"
                @change="changeComputeType"
                >自动结算</a-radio
              >
            </div>
            <span style="font-size: 11px; flex: 1; margin-top: 3px">
              到结算日期后系统会自动生成付款单，如审批中未设置流程节点，则改选项不可选中
            </span>
          </div>
        </div>
      </div>

      <template #footer>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <div>
            <a-checkbox
              :checked="settle_param.is_check == 1"
              @change="
                () =>
                  (settle_param.is_check = settle_param.is_check == 0 ? 1 : 0)
              "
              >勾选，代表确定知晓操作带来的影响
            </a-checkbox>
          </div>
          <div>
            <a-button type="" @click="cycleVisible = false">取消</a-button>
            <a-button
              type="primary"
              @click="saveSettleInfo"
              :disabled="!settle_param.is_check"
              >保存</a-button
            >
          </div>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { ref, reactive, createVNode, watch, toRefs } from "vue";
import { Modal, message } from "ant-design-vue";
import {
  PlusOutlined,
  EditOutlined,
  MoreOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import CommissionRule from "./modules/CommissionRule.vue";
import SettlementList from "./modules/SettlementList.vue";
import request from "../../../common/utils/request";
import {
  RightOutlined,
  UnlockOutlined,
  LockOutlined,
} from "@ant-design/icons-vue";
export default {
  components: {
    ExclamationCircleOutlined,
    CommissionRule,
    SettlementList,
    PlusOutlined,
    EditOutlined,
    RightOutlined,
    UnlockOutlined,
    LockOutlined,
    MoreOutlined,
  },
  setup() {
    const state = reactive({
      logItem: {},
      logStatus: 1,
      channel_config: [],
      manage_config: [],
      divide_config: [],
    });
    const activeKey = ref("rule");

    // 获取佣金规则
    const page = ref(1);
    const total = ref(0);
    const limit = ref(10);
    const ruleList = ref([]);
    const getRuleList = () => {
      request
        .get("/org", "/business/customer/commissionList", {
          page: page.value,
          limit: limit.value,
        })
        .then((res) => {
          console.log(res);
          ruleList.value = res.list;
          total.value = res.total;
        });
    };

    getRuleList();
    const handleTabChange = () => {
      if (activeKey.value == "rule") {
        getRuleList();
      }
    };

    const handlePageChange = (pager, pageSize) => {
      page.value = pager;
      limit.value = pageSize;
      getRuleList();
    };

    // 佣金规则
    const editId = ref(0);
    const ruleVisible = ref(false);
    const addRule = () => {
      ruleVisible.value = true;
    };
    // 编辑
    const editRule = (val) => {
      editId.value = val;
      ruleVisible.value = true;
    };

    const resetInfo = () => {
      editId.value = 0;
      ruleVisible.value = false;
    };
    const ruleClose = () => {
      resetInfo();
    };
    const refreshList = () => {
      resetInfo();
      page.value = 1;
      getRuleList();
    };

    // 禁用
    const changeRule = (item) => {
      let msg = item.status == 1 ? "确定禁用该规则？" : "确定启用该规则？";
      Modal.confirm({
        title: "提示?",
        icon: createVNode(ExclamationCircleOutlined),
        content: msg,
        onOk() {
          request
            .put("/org", "/business/customer/commissionEnable", {
              id: item.id,
              // status: item.status == 1 ? 0 : 1,
            })
            .then((res) => {
              message.success("操作成功");
              page.value = 1;
              getRuleList();
            });
        },
        onCancel() {},
      });
    };

    const settle_param = reactive({
      settle_type: 1,
      date: 1, //每月的几号、
      compute_type: 1, //结算方式;1=手动结算2=自动结算
      is_check: 0, // 是否勾选协议;0=否1=是
    });

    // 结算周期相关
    const getConfig = () => {
      request.get("/org", "/business/customer/getSettleConfig").then((res) => {
        console.log(res);
        settle_param.settle_type = res.data.settle_type;
        settle_param.date = res.data.date;
        settle_param.compute_type = res.data.compute_type;
        settle_param.is_check = 0; //默认不勾选。提交的时候必须去勾选一下
      });
    };

    const cycleVisible = ref(false);
    const settlementCycle = () => {
      getConfig();
      cycleVisible.value = true;
    };

    const closeSetCycle = () => {
      cycleVisible.value = false;
    };

    const changeSettleType = () => {
      settle_param.settle_type = settle_param.settle_type == 1 ? 2 : 1;
    };
    const changeComputeType = () => {
      settle_param.compute_type = settle_param.compute_type == 1 ? 2 : 1;
    };

    const settlement = ref();
    const saveSettleInfo = () => {
      request
        .post("/org", "/business/customer/saveSettleConfig", settle_param)
        .then((res) => {
          message.success(res.msg || "设置成功");
          cycleVisible.value = false;
          settlement.value.getConfig();
        });
    };

    // 日志
    const logList = ref([]);
    const getLogList = (tempId) => {
      const param = {
        page: 1,
        limit: 999,
        template_id: tempId,
      };
      request
        .get("/org", "/business/customer/commissionLogList", param)
        .then((res) => {
          console.log(res);
          logList.value = res.list;
        });
    };

    const logVisible = ref(false);
    const logInfo = (val) => {
      console.log(val);
      logVisible.value = true;
      state.logStatus = val.status;
      getLogList(val.id);
    };
    const onClose = () => {
      logVisible.value = false;
    };
    const logDetailVisible = ref(false);
    const showLogDetail = (val, index) => {
      console.log(val, index);
      state.logItem = val;
      state.logItem.index = index;
      console.log(state.logItem);
      state.divide_config = val.content.divide_config;
      state.manage_config = val.content.manage_config;
      state.channel_config = val.content.channel_config;
      logDetailVisible.value = true;
    };
    const onCloseDetail = () => {
      logDetailVisible.value = false;
    };

    const commissionColumns = [
      {
        title: "档位名称",
        key: "title",
      },
      {
        title: "档位下限",
        key: "threshold",
      },
      {
        title: "提成",
        key: "divide_num",
      },
    ];
    const commissionData = ref([]);

    const handleOk = () => {
      console.log("ok");
      cycleVisible.value = false;
    };

    return {
      ...toRefs(state),
      activeKey,
      addRule,
      changeRule,
      editRule,
      logInfo,
      logVisible,
      logList,
      onClose,
      showLogDetail,
      logDetailVisible,
      onCloseDetail,
      commissionColumns,
      commissionData,
      settlementCycle,
      closeSetCycle,
      cycleVisible,
      ruleVisible,
      handleOk,
      settle_param,
      changeSettleType,
      changeComputeType,
      saveSettleInfo,
      ruleClose,
      refreshList,
      ruleList,
      editId,
      handleTabChange,
      settlement,
      page,
      total,
      handlePageChange,
    };
  },
};
</script>

<style lang="less" scoped>
.box {
  padding: 12px;
  overflow: auto;
  .commission {
    display: flex;
    flex-wrap: wrap;
    padding: 0 10px 15px;

    .rule {
      width: 25%;
      height: 250px;
      padding: 15px 15px 0 0;
      box-sizing: border-box;

      .rule-content {
        position: relative;
        height: 100%;
        border: 1px solid #ccc;
        border-radius: 10px;
        overflow: hidden;
        color: #666;

        .rule-header {
          height: 40px;
          line-height: 40px;
          padding: 0px 10px;
          border-bottom: 1px solid #ccc;
        }

        .rule-body {
          .rule-text {
            height: 30px;
            line-height: 30px;
            padding: 0 10px;
          }
        }

        .rule-action {
          background-color: #ededed;
          position: absolute;
          left: 0;
          right: 0;
          bottom: 0;
          height: 40px;
          line-height: 40px;
          text-align: center;
        }
      }
    }
  }
}

.log-title {
  margin: 10px 0;
  font-size: 18px;
  color: #333;
  font-weight: 700;
}

.rule-box {
  width: 100%;
  overflow-y: auto;
  padding: 10px 20px 20px;
  overflow-x: hidden;
  .content {
    overflow: hidden;
  }
  .add-template {
    width: 100%;
    height: 230px;
    border: 1px dashed #d9d9d9;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #929292;
    cursor: pointer;
    font-size: 20px;
  }
  .icon {
    font-size: 48px;
    color: @primary-color;
  }
  .templat-list {
    width: 100%;
    height: 100%;
    .card-list {
      height: 140px;
      overflow-y: auto;
    }
  }
}

:deep(.ant-tabs-content) {
  height: 100%;
}
:deep(.ant-tabs-nav) {
  padding: 0 10px;
}

:deep(.ant-alert-description) {
  font-size: 12px;
  p {
    margin-bottom: 6px;
  }
}
:deep(.ant-alert-with-description.ant-alert-no-icon) {
  padding: 6px 10px;
}
</style>
